package com.yinxing.webapi.code.service.sys;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yinxing.framework.exception.OperationException;
import com.yinxing.framework.mybatis.TemplateService;
import com.yinxing.webapi.code.entity.sys.SysConfig;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.time.LocalDateTime;

@Slf4j
@Service
@Transactional
public class ISysConfigService extends TemplateService<SysConfig> {

    @Override
    public boolean insert(SysConfig entity) {
        entity.setUpdateTime_(LocalDateTime.now());
        return super.insert(entity);
    }

    @Override
    public boolean updateById(SysConfig entity) {
        entity.setUpdateTime_(LocalDateTime.now());
        //重新设置系统日志级别
        if("logback_log_level".equals(entity.getConfigKey_())) {
            this.resetSystemLogLevel(entity);
        }
        return super.updateById(entity);
    }

    @Override
    public boolean deleteById(Serializable id) {
        SysConfig config = super.selectById(id);
        if(config != null && config.getSystemIn_() == Boolean.TRUE) {
            throw new OperationException("系统内置配置不允许删除");
        }
        return super.deleteById(id);
    }

    /**
     * 根据配置键名查询
     * @param configKey 配置键名
     */
    public SysConfig getSysConfig(String configKey) {
        QueryWrapper<SysConfig> qw = new QueryWrapper<>();
        qw.eq("ConfigKey_", configKey);
        return selectOne(qw);
    }

    /**
     * 重新设置系统日志级别
     */
    private void resetSystemLogLevel(SysConfig config) {
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        Logger root = loggerContext.getLogger("root");
        String level = config.getConfigValue_().toLowerCase().trim();
        log.info("根据系统配置信息.设置系统日志级别 - 设置前级别:{} 设置后级别:{}", root.getLevel(), level);
        switch (level) {
            case "trace":
                root.setLevel(Level.TRACE);
                break;
            case "debug" :
                root.setLevel(Level.DEBUG);
                break;
            case "info" :
                root.setLevel(Level.INFO);
                break;
            case "warn" :
                root.setLevel(Level.WARN);
                break;
            case "ERROR" :
                root.setLevel(Level.ERROR);
                break;
        }
    }
}